﻿using B.S.BaseData.ErrorCode;
using B.S.Passport.Domain;
using Dapper;
using MediatR;
using Microsoft.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using DAL;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.StoreCommand;
using B.S.BaseData.Manage.Api.Read.DTO;

namespace B.S.BaseData.Manage.Api.Read.ApiAction.CommandHandler.StoreCommandHandler
{
    /// <summary>
    /// 入库Id查询
    /// </summary>
    public class StoreOnlyCommandHandler : IRequestHandler<StoreOnlyCommand, ApiReqult<List<ManagementModelDTO>>>
    {
        private readonly DBHelper bHelper;

        public StoreOnlyCommandHandler(DBHelper bHelper)
        {
            this.bHelper = bHelper;
        }

        /// <summary>
        /// 入库Id查询
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiReqult<List<ManagementModelDTO>>> Handle(StoreOnlyCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<List<ManagementModelDTO>>();

            try
            {
                // 假设根据 request 中的信息构建 SQL 查询语句
                //string sql = $"SELECT * FROM (SELECT mm.*, pm.ProductId, pm.ProductNum, pm.ProductName, pm.ManufacturerCode, pm.WHouseTypeId, pm.UnitId, pm.Category, pm.UpperLimit, pm.LowerLimit, pm.Specification, pm.Price, pm.WHouseId, pm.Supplie, pm.Customer, pm.Guige, pm.Description FROM ManagementModel mm LEFT JOIN ProductModel pm ON mm.Pid = pm.ProductId) AS joined_table WHERE Id = {request.Id} AND IsDelete = 0;    ";
                string sql = $"SELECT * from ManagementModels WHERE InboundNum = '{request.InboundNum}' AND IsDelete = 0;";
                 List<ManagementModelDTO>? hoModes= bHelper.GetList<ManagementModelDTO>(sql);

                var managementModel = bHelper.GetList<ManagementModelDTO>(sql);

                    if (managementModel != null)
                    { 
                        result.Data = hoModes;
                        result.Msg = ApiEnum.查询成功.ToString();
                    }
                    else
                    {
                        result.Msg = ApiEnum.查询失败.ToString();
                        result.Code = ApiEnum.查询失败;
                    }
                
            }
            catch (SqlException ex)
            {
                result.Msg = ApiEnum.查询失败.ToString();
                result.Code = ApiEnum.查询失败;
            }

            return result;
        }
    }
}